<?php
$db = new Database();
$fs = new Functions();
$set_date_time = $fs->set_default_timezone_datetime();
$auth = Auth::getAuth('current_user');
$result = array();
error_reporting(0);
if($_SERVER['REQUEST_METHOD'] == "POST" && isset($_POST)){
    
    if(isset($_POST['action'])){
        
        $Mail_Notifications = new Mail_Notifications();
        
        // Reset Password
        if($_POST['action'] == "reset_password"){
            $email = $_POST['email'];
            
            $serverName = $fs->curPageURL("serverName");
            
            // Select User
            $user = $db->query("SELECT * FROM " . $db->tbl_name(TB_USERS) . " WHERE email={$db->escape($email)}","row");
            
            $password = $fs->random_chars("10");
            
            $encryted_userID = $fs->encrypt_decrypt("encrypt", $user['id']);
            
            $encrypt_password = $fs->encrypt_decrypt("encrypt", $password);
            
            //$url = $serverName . "/reset_password?id=" . $encryted_userID;
            
            $Accounts = new Accounts($db,$user['account_id']);
            $update = array("password"  =>  $encrypt_password);
            $condition = array("id" =>  $Accounts->user_id);
            $db->update($db->tbl_name(TB_USERS),$update,$condition);
            
            $name = $Accounts->first_name . " " . $Accounts->last_name;
            
            $array = array( "generated_password"    =>  $password,
                            "reset_password_url"    =>  $serverName,
                            "to"                    =>  array($user['email']    =>  $name),
                            "cc"                    =>  "",
                            "bcc"                   =>  "");
            
            $Mail_Notifications->mail_reset_password($array);
            
            $return = array("msg"               =>  "Your password was successfully reset, Please visit your email and get your password.",
                            "notification"      =>  "Ok");
            
            echo json_encode($return);
             
            $fs->save_audit_logs($db,$user['id'],"3","tb_users",$set_date_time['date_time'],$user['id']);
        }
        
        else{
            $this->setLayout();
        }
    }else{
        $this->setLayout();
    }
}else{
    $this->setLayout();
}
?>